<template>
  <v-card class="pa-6" width="400" elevation="8">
    <v-tabs v-model="tab" align-tabs="center">
      <v-tab value="login">登录</v-tab>
      <v-tab value="register">注册</v-tab>
    </v-tabs>

    <v-window v-model="tab">
      <v-window-item value="login">
        <v-text-field v-model="loginForm.username" label="用户名" />
        <v-text-field v-model="loginForm.password" label="密码" type="password" />
        <v-btn color="primary" block class="mt-4" @click="handleLogin">登录</v-btn>
      </v-window-item>

      <v-window-item value="register">
        <v-text-field v-model="registerForm.username" label="用户名" />
        <v-text-field v-model="registerForm.email" label="邮箱" />
        <v-text-field v-model="registerForm.password" label="密码" type="password" />
        <v-btn color="primary" block class="mt-4" @click="handleRegister">注册</v-btn>
      </v-window-item>
    </v-window>
  </v-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { initSubscriptionsFromToken, parseJwt } from '@/composables/initSubscriptions'

const emit = defineEmits(['login-success'])

const tab = ref('login')
const loginForm = ref({ username: '', password: '' })
const registerForm = ref({ username: '', email: '', password: '' })

async function handleLogin() {
  try {
    const res = await axios.post(
      'http://localhost:8080/api/user/login',
      loginForm.value,
      {
        auth: { username: 'admin', password: '123456' },
        headers: { 'Content-Type': 'application/json' },
      }
    )

    const token = res.data
    const payload = parseJwt(token)
    const userId = payload?.userId
    if (!userId) throw new Error('❌ 无法从 token 获取 userId')

    // 保存 token 和 userId
    localStorage.setItem('jwt_token', token)
    localStorage.setItem('user_id', String(userId))

    // ✅ 初始化 STOMP 连接和消息订阅
    await initSubscriptionsFromToken(token)

    console.log('✅ 登录成功，完成订阅')
    emit('login-success', token)
  } catch (err) {
    console.error('❌ 登录失败', err)
  }
}

async function handleRegister() {
  try {
    await axios.post(
      'http://localhost:8080/api/user/register',
      registerForm.value,
      {
        auth: { username: 'admin', password: '123456' },
        headers: { 'Content-Type': 'application/json' },
      }
    )
    tab.value = 'login'
  } catch (err) {
    console.error('❌ 注册失败', err)
  }
}
</script>
